package com.cms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cms.common.StringUtils;
import com.cms.constant.CmsConstant;
import com.cms.model.TrAdminUser;
import com.cms.model.TrUserRole;
import com.cms.service.AdminUserService;
import com.cms.service.ReportService;
import com.cms.service.UserRoleService;
import com.google.gson.Gson;
import com.cms.common.MD5Util;

@Controller
public class ManagerController extends BaseController {

	@Autowired
	private AdminUserService adminService;

	@Autowired
	private ReportService reportService;

	@Autowired
	private UserRoleService userRoleService;

	@RequestMapping(value = "/admin.do")
	public String enter(HttpServletRequest req, HttpServletResponse resp,
			ModelMap map) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put(CmsConstant.CATALOG_NAME, CmsConstant.USER_STATUS);
		map.put("USER_STATUS", this.reportService.getReportResult(
				CmsConstant.CATALOG_CODE, param));
		return "admin/userMain.html";
	}

	@RequestMapping("/admin/userList.do")
	public String userList(HttpServletRequest req, HttpServletResponse resp,
			ModelMap map) throws Exception {
		Map<String, Object> param = buildQueryMap(req);
		map.put("managerList", this.reportService.pagingReportResult(
				"pagingManagerList", param));
		return "admin/userList.html";
	}

	@RequestMapping("/admin/changeUserStatus.do")
	public void changeUserStatus(HttpServletRequest req,
			HttpServletResponse resp, ModelMap map) throws Exception {
		String userId = req.getParameter("userId");
		String status = req.getParameter("userStatus");
		TrAdminUser tu = new TrAdminUser();
		tu.setId(StringUtils.str2Int(userId));
		tu.setUserStatus(status);
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			TrAdminUser admin = new TrAdminUser();
			tu.setModifyUser(admin.getId());
			this.adminService.changeUserStatus(tu);
			result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
		} catch (Exception e) {
			result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
			result.put(CmsConstant.MSG, e.getMessage());
		}
		this.renderText(resp, new Gson().toJson(result));
	}

	/***
	 * 注册用户
	 */
	@RequestMapping(value = "/admin/register.do")
	public void register(HttpServletRequest req, HttpServletResponse resp,
			ModelMap map) throws Exception {
		TrAdminUser current = this.getLoginUser(req);
		TrAdminUser tu = new TrAdminUser();
		this.export(req, "admin", tu);
		tu.setCreateUser(current.getId());
		tu.setModifyUser(current.getId());
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			tu.setUserPassword(MD5Util.MD5(tu.getUserPassword()));
			TrAdminUser au = adminService.login(tu);
			if (au == null) {
				this.adminService.register(tu);
				this.userRoleService.deleteUserRole(tu.getId());
				TrAdminUser admin = this.getLoginUser(req);
				String[] roleName = req.getParameterValues("role");
				if (roleName != null && !ArrayUtils.isEmpty(roleName)) {
					List<TrUserRole> roles = new ArrayList<TrUserRole>();
					TrUserRole role = null;
					for (int i = 0; roleName != null && i < roleName.length; i++) {
						role = new TrUserRole();
						role.setRoleId(StringUtils.str2Int(roleName[i]));
						role.setUserId(tu.getId());
						role.setModifyUser(admin.getId());
						roles.add(role);
					}
					this.userRoleService.addUserRole(roles);
				} 
				result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
			}
			else
			{
				result.put(CmsConstant.STATUS, CmsConstant.FAIL_STATUS);
				result.put(CmsConstant.MSG, au.getUserLoginName()+"已经存在，无法继续添加。");
			}
		} catch (Exception e) {
			result.put(CmsConstant.STATUS, CmsConstant.FAIL_STATUS);
			result.put(CmsConstant.MSG, e.getMessage());
		}
		this.renderText(resp, new Gson().toJson(result));
	}

	/***
	 * 修改用户
	 */
	@RequestMapping(value = "/admin/updateAdminUser.do")
	public void updateAdminUser(HttpServletRequest req,
			HttpServletResponse resp, ModelMap map) throws Exception {
		TrAdminUser current = this.getLoginUser(req);
		TrAdminUser tu = new TrAdminUser();
		this.export(req, "admin", tu);
		tu.setModifyUser(current.getId());
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			this.userRoleService.deleteUserRole(tu.getId());
			TrAdminUser admin = this.getLoginUser(req);
			String[] roleName = req.getParameterValues("role");
			if (roleName != null && !ArrayUtils.isEmpty(roleName)) {
				List<TrUserRole> roles = new ArrayList<TrUserRole>();
				TrUserRole role = null;
				for (int i = 0; roleName != null && i < roleName.length; i++) {
					role = new TrUserRole();
					role.setRoleId(StringUtils.str2Int(roleName[i]));
					role.setUserId(tu.getId());
					role.setModifyUser(admin.getId());
					roles.add(role);
				}
				this.userRoleService.addUserRole(roles);
			}
			this.adminService.updateUserInfo(tu);
			result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
		} catch (Exception e) {
			result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
			result.put(CmsConstant.MSG, e.getMessage());
		}
		this.renderText(resp, new Gson().toJson(result));
	}

	@RequestMapping(value = "/admin/userInfo.do")
	public String userInfo(HttpServletRequest req, HttpServletResponse resp,
			ModelMap map) throws Exception {
		map.put("user", this.getLoginUser(req));
		return "admin/userSelfInfo.html";
	}

	@RequestMapping(value = "/admin/toEditUserInfo.do")
	public String toEditUserInfo(HttpServletRequest req,
			HttpServletResponse resp, ModelMap map) throws Exception {
		int userId = StringUtils.str2Int(req.getParameter("userId"));
		TrAdminUser tu = new TrAdminUser();
		tu.setId(userId);
		map.put("user", this.adminService.getUserInfo(tu));
		map.put("action", "/admin/updateAdminUser.do");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put(CmsConstant.CATALOG_NAME, CmsConstant.USER_STATUS);
		map.put("USER_STATUS", this.reportService.getReportResult(
				CmsConstant.CATALOG_CODE, param));
		map.put("userRoleList",
				this.reportService.getReportResult("getUserRoleInfo",
						this.buildQueryMap(req)));
		return "admin/userInfo.html";
	}

	@RequestMapping(value = "/admin/toRegUserInfo.do")
	public String totoRegUserInfo(HttpServletRequest req,
			HttpServletResponse resp, ModelMap map) throws Exception {
		TrAdminUser tu = new TrAdminUser();
		map.put("user", tu);
		map.put("action", "/admin/register.do");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put(CmsConstant.CATALOG_NAME, CmsConstant.USER_STATUS);
		map.put("USER_STATUS", this.reportService.getReportResult(
				CmsConstant.CATALOG_CODE, param));
		map.put("userRoleList",
				this.reportService.getReportResult("getUserRoleInfo",
						this.buildQueryMap(req)));
		return "admin/userInfo.html";
	}

	@RequestMapping(value = "/admin/saveUserInfo.do")
	public void saveUserInfo(HttpServletRequest req,
			HttpServletResponse resp, ModelMap map) throws Exception {
		Map<String,Object>result = new HashMap<String, Object>();
		TrAdminUser au = this.getLoginUser(req);
		this.export(req, "admin", au);
		String userPassword =req.getParameter("userPassword");
		boolean bol =true;
		if(!StringUtils.isBlank(userPassword))//用户的旧密码不为空
		{
			String passwordStr = MD5Util.MD5(userPassword);
			if(!StringUtils.equals(passwordStr, au.getUserPassword()))
			{
				result.put(CmsConstant.STATUS, CmsConstant.FAIL_STATUS);
				result.put(CmsConstant.MSG, "旧密码输入错误!");
				bol=false;
			} 
			else
			{
				 au.setUserPassword(MD5Util.MD5(req.getParameter("confirmUserPassword")));
			}
		} 
		if(bol)
		{ 
				try
				{ 
				     this.adminService.updateSelfUserInfo(au);
				     result.put(CmsConstant.STATUS, CmsConstant.SUCCESS_STATUS);
				}catch (Exception e) {
					result.put(CmsConstant.STATUS, CmsConstant.FAIL_STATUS);
					result.put(CmsConstant.MSG, e.getMessage());
				} 
		}
		this.renderText(resp, new Gson().toJson(result));
	}

}
